/**
 * 智能对话组件
 */
const ChatView = {
    name: 'ChatView',
    props: {
        loading: {
            type: Boolean,
            default: false
        },
        messages: {
            type: Array,
            default: () => []
        },
        settings: {
            type: Object,
            default: () => ({
                model: 'glm-4.5-flash',
                temperature: 1,
                max_tokens: 65536
            })
        }
    },
    emits: ['send-message', 'clear-conversation', 'stop-stream'],
    data() {
        return {
            inputText: '',
            currentAssistantMessage: '' // 用于流式显示
        };
    },
    methods: {
        submit() {
            if (this.inputText.trim() && !this.loading) {
                this.$emit('send-message', this.inputText);
                this.inputText = '';
            }
        },
        stopStream() {
            this.$emit('stop-stream');
        },
        clearConversation() {
            this.$confirm('确定要清除所有消息吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$emit('clear-conversation');
            }).catch(() => {});
        },
        scrollToBottom() {
            // 滚动到底部
            this.$nextTick(() => {
                const messageContainer = this.$refs.messageContainer;
                if (messageContainer) {
                    // 使用平滑滚动
                    messageContainer.scrollTo({
                        top: messageContainer.scrollHeight,
                        behavior: 'smooth'
                    });
                }
            });
        },
        // 将Markdown转换为HTML
        renderMarkdown(content) {
            if (!content) return '';
            // 检查marked是否可用
            if (typeof marked !== 'undefined') {
                try {
                    // 配置marked选项
                    marked.setOptions({
                        breaks: true, // 支持换行
                        gfm: true, // 支持GitHub风格的Markdown
                        headerIds: false, // 禁用标题ID
                        mangle: false // 禁用邮箱混淆
                    });
                    return marked.parse(content);
                } catch (e) {
                    console.error('Markdown解析错误:', e);
                    return content;
                }
            }
            // 如果marked不可用，返回原文本
            return content;
        },
        // 将Markdown转换为HTML并添加闪烁光标（用于流式消息）
        renderMarkdownWithCursor(content) {
            const html = this.renderMarkdown(content);
            // 在HTML末尾添加闪烁光标
            return html + '<span style="display: inline-block; width: 2px; height: 14px; background-color: #409EFF; margin-left: 2px; animation: blink 1s infinite; vertical-align: middle;"></span>';
        }
    },
    watch: {
        // 监听loading状态，重置流式消息
        loading(newVal) {
            if (!newVal) {
                this.currentAssistantMessage = '';
            }
        },
        // 监听消息变化，自动滚动到底部
        messages: {
            handler() {
                this.scrollToBottom();
            },
            deep: true
        },
        // 监听流式消息变化，自动滚动到底部
        currentAssistantMessage() {
            this.scrollToBottom();
        }
    },
    template: `
        <el-card shadow="hover" style="margin: 20px;">
            <div slot="header">
                <span style="font-size: 18px; font-weight: 600;">智能对话</span>
                <p style="margin: 8px 0 0 0; color: #909399; font-size: 14px;">与AI助手进行对话交流</p>
            </div>
            
            <!-- 消息区域 -->
            <div ref="messageContainer" style="min-height: 400px; max-height: 500px; overflow-y: auto; margin-bottom: 20px; padding: 15px; background-color: #f5f7fa; border-radius: 4px;">
                <div v-if="messages.length === 0" style="text-align: center; padding: 60px 20px; color: #909399;">
                    <i class="el-icon-chat-line-round" style="font-size: 48px; margin-bottom: 10px;"></i>
                    <p>开始您的对话吧！</p>
                </div>
                <div 
                    v-for="(msg, index) in messages" 
                    :key="index" 
                    :style="msg.role === 'user' 
                        ? 'display: flex; justify-content: flex-end; margin-bottom: 12px;' 
                        : 'display: flex; justify-content: flex-start; margin-bottom: 12px;'"
                >
                    <!-- 用户消息：纯文本显示 -->
                    <div 
                        v-if="msg.role === 'user'"
                        style="
                            max-width: 70%; 
                            padding: 10px; 
                            word-wrap: break-word; 
                            font-size: 14px; 
                            display: inline-block;
                            background-color: #409EFF;
                            color: #fff;
                            border-radius: 6px;
                            box-sizing: border-box;
                        "
                    >
                        {{ msg.content }}
                    </div>
                    <!-- AI消息：Markdown渲染 -->
                    <div 
                        v-else
                        style="
                            max-width: 70%; 
                            padding: 10px; 
                            word-wrap: break-word; 
                            font-size: 14px; 
                            display: inline-block;
                            background-color: #fff;
                            color: #303133;
                            border: 1px solid #e4e7ed;
                            border-radius: 6px;
                            box-sizing: border-box;
                        "
                        v-html="renderMarkdown(msg.content)"
                    >
                    </div>
                </div>
                <!-- 流式显示当前正在生成的消息（只在有内容时显示） -->
                <div v-if="loading && currentAssistantMessage" style="display: flex; justify-content: flex-start; margin-bottom: 12px;">
                    <div 
                        style="
                            max-width: 70%; 
                            padding: 6px 10px; 
                            word-wrap: break-word; 
                            white-space: pre-wrap; 
                            line-height: 1.4; 
                            font-size: 14px; 
                            display: inline-block;
                            background-color: #fff;
                            color: #303133;
                            border: 1px solid #e4e7ed;
                            border-radius: 6px;
                        "
                        v-html="renderMarkdownWithCursor(currentAssistantMessage)"
                    >
                    </div>
                </div>
                <!-- 只在没有任何消息且正在加载时显示"正在思考" -->
                <div v-else-if="loading && messages.length === 0" style="display: flex; justify-content: flex-start; margin-bottom: 12px;">
                    <div style="
                        max-width: 70%; 
                        padding: 6px 10px; 
                        word-wrap: break-word; 
                        white-space: pre-wrap; 
                        line-height: 1.4; 
                        font-size: 14px; 
                        display: inline-block;
                        background-color: #fff;
                        color: #303133;
                        border: 1px solid #e4e7ed;
                        border-radius: 6px;
                    ">
                        <i class="el-icon-loading" style="margin-right: 6px;"></i>
                        <span style="color: #909399;">正在思考...</span>
                    </div>
                </div>
                
                <style>
                    @keyframes blink {
                        0%, 100% { opacity: 1; }
                        50% { opacity: 0; }
                    }
                </style>
            </div>
            
            <!-- 输入区域 -->
            <div style="display: flex; align-items: flex-end; gap: 8px;">
                <el-input
                    v-model="inputText"
                    type="textarea"
                    :rows="2"
                    placeholder="输入您的问题..."
                    @keyup.enter.native.exact="submit"
                    @keyup.shift.enter.native="inputText += '\\n'"
                    style="flex: 1;"
                >
                </el-input>
                <el-button 
                    type="info" 
                    @click="stopStream"
                    :disabled="!loading"
                    icon="el-icon-close"
                    style="flex-shrink: 0;"
                    circle
                    title="停止当前回复"
                >
                </el-button>
                <el-button 
                    type="default" 
                    @click="clearConversation"
                    :disabled="loading || messages.length === 0"
                    icon="el-icon-delete"
                    style="flex-shrink: 0;"
                    circle
                >
                </el-button>
                <el-button 
                    type="primary" 
                    @click="submit"
                    :loading="loading"
                    :disabled="!inputText.trim()"
                    icon="el-icon-position"
                    style="flex-shrink: 0;"
                >
                    发送
                </el-button>
            </div>
        </el-card>
    `
};